package com.jlwl.houseservice.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jlwl.houseservice.common.Result;
import com.jlwl.houseservice.entity.Order;
import com.jlwl.houseservice.service.OrderService;
import com.jlwl.houseservice.vo.OrderCreateVO;
import com.jlwl.houseservice.vo.OrderDetailVO;
import com.jlwl.houseservice.vo.OrderQueryVO;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public Result<Map<String, Object>> createOrder(@Valid @RequestBody OrderCreateVO orderCreateVO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 创建订单
        String orderNo = orderService.createOrder(orderCreateVO, userId);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("orderNo", orderNo);
        
        return Result.success(result);
    }

    /**
     * 获取订单列表
     */
    @GetMapping
    @PreAuthorize("hasRole('USER')")
    public Result<Page<Order>> list(OrderQueryVO queryVO) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 查询订单列表
        Page<Order> page = orderService.pageList(queryVO, userId);
        
        return Result.success(page);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{orderNo}")
    @PreAuthorize("hasRole('USER')")
    public Result<OrderDetailVO> getDetail(@PathVariable String orderNo) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 获取订单详情
        OrderDetailVO detailVO = orderService.getOrderDetail(orderNo, userId);
        if (detailVO == null) {
            return Result.error("订单不存在");
        }
        
        return Result.success(detailVO);
    }

    /**
     * 取消订单
     */
    @PutMapping("/{orderNo}/cancel")
    @PreAuthorize("hasRole('USER')")
    public Result<Void> cancelOrder(@PathVariable String orderNo, @RequestParam String reason) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 取消订单
        boolean success = orderService.cancelOrder(orderNo, userId, reason);
        if (!success) {
            return Result.error("取消订单失败");
        }
        
        return Result.success();
    }

    /**
     * 完成订单
     */
    @PutMapping("/{orderNo}/complete")
    @PreAuthorize("hasRole('USER')")
    public Result<Void> completeOrder(@PathVariable String orderNo) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 从用户名中提取用户ID（实际项目中应该从UserDetails中获取）
        Integer userId = getUserIdFromUsername(username);
        
        // 完成订单
        boolean success = orderService.completeOrder(orderNo, userId);
        if (!success) {
            return Result.error("完成订单失败");
        }
        
        return Result.success();
    }

    /**
     * 从用户名中提取用户ID
     * 实际项目中应该从UserDetails中获取
     */
    private Integer getUserIdFromUsername(String username) {
        // 这里简化处理，实际项目中应该从UserDetails中获取
        return 1;
    }
} 